package opn.srn.command.mongodb;

import java.net.UnknownHostException;
import java.util.Map;
import java.util.Map.Entry;

import opn.srn.command.Command;
import opn.srn.command.ICommand;
import opn.srn.common.SimpleMessage;
import opn.srn.event.EventConstants;
import opn.srn.event.IEvent;
import opn.srn.event.SimpleEvent;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

public class PersistCommand extends Command {

	public static final String NAME = "mongopersist";
	DBCollection persistTable;

	public PersistCommand() {
		super(NAME);
	}

	@Override
	public void load(Map<String, String> parameter) throws Exception {
	}

	@Override
	public void onEvent(ICommand<?> source, IEvent event) throws Exception {
		int type = event.getType();
		switch (type) {
		case EventConstants.CMD_START: {
			initializeDB();
			break;
		}
		case EventConstants.CMD_DATA: {
			if (event instanceof SimpleEvent && event.getData() instanceof SimpleMessage) {
				persistData((SimpleMessage) event.getData());
			}
			break;
		}
		}
		super.onEvent(source, event);
	}

	private void persistData(SimpleMessage message) {
		if (message == null) {
			return;
		}

		BasicDBObject document = new BasicDBObject();
		for (Entry<String, Object> value : message.getAllDatas().entrySet()) {
			document.put(value.getKey(), value.getValue());
		}
		persistTable.insert(document);
	}

	private void initializeDB() throws UnknownHostException {
		MongoClient mongo = new MongoClient();
		DB db = mongo.getDB("persistdb");
		persistTable = db.getCollection("persist");
	}

}
